package com.bw.module_home.ui

import android.annotation.SuppressLint
import android.content.DialogInterface
import android.os.Build
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.view.ContextThemeWrapper
import android.view.GestureDetector
import android.view.Gravity
import android.view.MotionEvent
import android.widget.PopupMenu
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.activity.viewModels
import androidx.annotation.RequiresApi
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bw.lib_common.arouter.Router
import com.bw.lib_common.base.BaseActivity
import com.bw.lib_common.base.BaseViewModel
import com.bw.module_home.R
import com.bw.module_home.databinding.ActivityRepairManagerBinding
import com.bw.module_home.repair.adapter.RepairAdapter
import com.bw.module_home.repair.model.RepairEntityItem
import com.bw.module_home.repair.viewmodel.RepairViewModel
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
@Route(path = Router.Ui.RepairManagerActivity)
class RepairManagerActivity : BaseActivity<RepairViewModel, ActivityRepairManagerBinding>() {
    override val mLayoutResId: Int
        get() = R.layout.activity_repair_manager

    lateinit var repairAdapter: RepairAdapter
    private val viewModel: RepairViewModel by viewModels()
    private val repairList = mutableListOf<RepairEntityItem>()

    @RequiresApi(Build.VERSION_CODES.M)
    override fun initView() {
        super.initView()
        mBinding.repairBack.setOnClickListener {
            finish()
        }
        mBinding.floating.setOnClickListener {
            ARouter.getInstance().build("/repair/add_repair").navigation()
        }
        repairAdapter = RepairAdapter()
        mBinding.repairRv.adapter = repairAdapter
        mBinding.repairRv.layoutManager = LinearLayoutManager(this)
        viewModel.getRepairList()
        val detector = GestureDetector(this@RepairManagerActivity, object : GestureDetector.SimpleOnGestureListener() {
            override fun onLongPress(e: MotionEvent) {
                super.onLongPress(e)
                val childView = mBinding.repairRv.findChildViewUnder(e.x, e.y)
                val position = mBinding.repairRv.getChildAdapterPosition(childView!!)
                val id = repairAdapter.data[position].id
                AlertDialog.Builder(this@RepairManagerActivity)
                    .setTitle("是否删除维修订单?")
                    .setPositiveButton("确定", object : DialogInterface.OnClickListener {
                        override fun onClick(p0: DialogInterface?, p1: Int) {
                            viewModel.deleteRepair(id)
                        }
                    })
                    .setNegativeButton("取消", null)
                    .show()
            }
        })
        mBinding.repairRv.addOnItemTouchListener(object : RecyclerView.OnItemTouchListener {
            override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
                return detector.onTouchEvent(e)
            }

            override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {}

            override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {}
        })
        mBinding.llSort.setOnClickListener {
            AlertDialog.Builder(this)
                .setTitle("维修列表排序")
                .setItems(arrayOf("升序", "降序"), object : DialogInterface.OnClickListener {
                    override fun onClick(p0: DialogInterface?, p1: Int) {
                        when (p1) {
                            0 -> {
                                //升序
                                repairAdapter.data.sortBy { it.id }
                                repairAdapter.notifyDataSetChanged()
                                mBinding.ivSort.setImageResource(R.drawable.ic_sort_up)
                                mBinding.tvSort.setText("升序")
                            }
                            1 -> {
                                //降序
                                repairAdapter.data.sortByDescending { it.id }
                                repairAdapter.notifyDataSetChanged()
                                mBinding.ivSort.setImageResource(R.drawable.ic_sort_down)
                                mBinding.tvSort.setText("降序")
                            }
                        }
                    }
                })
                .setNegativeButton("取消", null)
                .show()
        }
        mBinding.etSearch.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {}

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                viewModel.getRepairOrderByName(p0.toString())
            }

            override fun afterTextChanged(p0: Editable?) {}
        })
        mBinding.ivSearch.setOnClickListener {
            viewModel.getRepairOrderByOrderNumber(mBinding.etSearch.text.toString())
        }
        val wrapper =
            ContextThemeWrapper(this, R.style.CustomPopupMenu)
        val popupMenu = PopupMenu(wrapper, mBinding.llFilter)
        popupMenu.menuInflater.inflate(R.menu.status_menu, popupMenu.menu)
        popupMenu.gravity = Gravity.BOTTOM
        mBinding.llFilter.setOnClickListener {
            popupMenu.show()
        }
        popupMenu.setOnMenuItemClickListener {
            repairAdapter.data.clear()
            title = it.title.toString()
            val list = repairList.filter {
                it.processingStatus == title
            }
            repairAdapter.data.addAll(list)
            repairAdapter.notifyDataSetChanged()
            false
        }
    }

//    override fun initListener() {
//        super.initListener()
//        viewModel.getRepairListSuccess.observe(this) {
//            repairList.addAll(it)
//            repairAdapter.data.clear()
//            repairAdapter.data.addAll(it)
//            repairAdapter.notifyDataSetChanged()
//        }
//        viewModel.deleteRepairSuccess.observe(this) {
//            Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show()
////            ToastUtils.showLong("删除成功")
//            viewModel.getRepairList()
//        }
//        viewModel.getRepairOrderByNumberSuccess.observe(this) {
//            repairAdapter.data.clear()
//            repairAdapter.data.add(it)
//            repairAdapter.notifyDataSetChanged()
//        }
//        viewModel.getRepairOrderByNameSuccess.observe(this) {
//            repairAdapter.data.clear()
//            repairAdapter.data.addAll(it)
//            repairAdapter.notifyDataSetChanged()
//        }
//    }
    override fun initListener() {
        super.initListener()
        viewModel.getRepairListSuccess.observe(this) { repairEntities ->
            repairList.clear()
            repairAdapter.data.clear()
            repairEntities.forEach { repairEntity ->
                repairList.addAll(repairEntity)
                repairAdapter.data.addAll(repairEntity)
            }
            repairAdapter.notifyDataSetChanged()
        }
        viewModel.deleteRepairSuccess.observe(this) {
            Toast.makeText(this, "删除成功", Toast.LENGTH_SHORT).show()
    //            ToastUtils.showLong("删除成功")
            viewModel.getRepairList()
        }
        viewModel.getRepairOrderByNumberSuccess.observe(this) {
            repairAdapter.data.clear()
            repairAdapter.data.addAll(it)
            repairAdapter.notifyDataSetChanged()
        }
        viewModel.getRepairOrderByNameSuccess.observe(this) { repairEntities ->
            repairAdapter.data.clear()
            repairEntities.forEach { repairEntity ->
                repairAdapter.data.addAll(repairEntity)
            }
            repairAdapter.notifyDataSetChanged()
        }
    }

    override fun onResume() {
        super.onResume()
        viewModel.getRepairList()
    }
}